<template>
  <div class="app-container">
    <!-- 页面说明 -->
    <div class="page-header">
      <h3>经理审核待办</h3>
      <p class="page-desc">显示主管已审核但经理未审核的员工考核数据</p>
    </div>

    <!-- 搜索表单 -->
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="员工姓名" prop="userName">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入员工姓名"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          v-hasPermi="['system:assessUser:list']"
        >搜索</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <div v-loading="loading">
      <el-collapse v-model="activeRoles" accordion>
        <el-collapse-item v-for="(group, idx) in rolesWithUsers" :key="group.roleKey || idx" :name="group.roleKey || String(idx)">
          <template slot="title">
            <span>角色：{{ group.roleName || '未分配角色' }}（{{ group.users.length }}人）</span>
          </template>
          <el-table :data="group.users" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="员工姓名" align="center" prop="userName" />
            <el-table-column label="部门" align="center" prop="deptName" />
            <el-table-column label="手机号码" align="center" prop="phonenumber" />
            <el-table-column label="状态" align="center" prop="status" width="100">
              <template slot-scope="scope">
                <el-tag :type="scope.row.status === '0' ? 'success' : 'danger'">
                  {{ scope.row.status === '0' ? '正常' : '停用' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="审核状态" align="center" width="150">
              <template slot-scope="scope">
                <div class="audit-status-display">
                  <!-- 主管审核状态 -->
                  <div class="audit-role-row">
                    <span class="role-label">主管:</span>
                    <el-tag 
                      :type="scope.row.supervisorAudited ? 'success' : 'info'"
                      size="mini"
                    >
                      {{ scope.row.supervisorAudited ? '已审核' : '未审核' }}
                    </el-tag>
                  </div>
                  
                  <!-- 经理审核状态 -->
                  <div class="audit-role-row">
                    <span class="role-label">经理:</span>
                    <el-tag 
                      :type="scope.row.managerAudited ? 'success' : 'info'"
                      size="mini"
                    >
                      {{ scope.row.managerAudited ? '已审核' : '未审核' }}
                    </el-tag>
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="创建时间" align="center" prop="createTime" width="180">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.createTime) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-view"
                  @click="handleViewCalendar(scope.row)"
                >查看考核</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-collapse-item>
      </el-collapse>
    </div>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 日历选择对话框 -->
    <el-dialog 
      title="选择考核日期" 
      :visible.sync="calendarOpen" 
      width="600px" 
      append-to-body
      :close-on-click-modal="false"
      class="calendar-dialog"
    >
      <div class="calendar-container">
        <div class="calendar-header">
          <span class="calendar-title">请选择要查看的考核日期</span>
          <span class="user-info">员工：{{ selectedUserInfo.userName || '' }}</span>
        </div>
        <el-calendar v-model="selectedDate" @select="handleDateSelect">
          <template slot="dateCell" slot-scope="{date, data}">
            <div class="calendar-day" :class="getDayClass(data)" @click="handleDayClick(data)">
              <span class="day-number">{{ data.day.split('-').slice(2).join('') }}</span>
              <div v-if="getDayScore(data.day)" class="day-score" :class="getScoreClass(getDayScore(data.day))">
                {{ getDayScore(data.day) }}
              </div>
              <div v-if="hasAssessData(data.day)" class="assess-indicator">
                <i class="el-icon-document"></i>
              </div>
            </div>
          </template>
        </el-calendar>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="calendarOpen = false">取 消</el-button>
        <el-button type="primary" @click="handleTodayClick">查看今日考核</el-button>
      </div>
    </el-dialog>

    <!-- 考核详情对话框 -->
    <el-dialog 
      :title="`${selectedUserInfo.userName || ''} - ${selectedDateForDetail} 考核详情`"
      :visible.sync="detailOpen" 
      width="95%" 
      append-to-body
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      class="detail-dialog"
      :before-close="handleDetailClose"
    >
      <div class="detail-header">
        <div class="detail-info">
          <span class="detail-title">考核详情</span>
          <span class="detail-date">{{ selectedDateForDetail }}</span>
          <span class="detail-user">员工：{{ selectedUserInfo.userName || '' }}</span>
        </div>
        <el-button 
          type="text" 
          icon="el-icon-close" 
          @click="detailOpen = false"
          class="close-btn"
        ></el-button>
      </div>
      <assess-user-detail 
        v-if="detailOpen" 
        :selected-date="selectedDateForDetail"
        :user-id="selectedUserId"
        :is-popup="true"
        @close="handleDetailClose"
        @submit-success="handleSubmitSuccess"
      />
    </el-dialog>
  </div>
</template>

<script>
import { getAssessRolesWithUsers } from "@/api/system/assessUser"
import AssessUserDetail from '../assessUser/detail.vue'

export default {
  name: "AssessManagerAudit",
  components: {
    AssessUserDetail
  },
  data() {
    return {
      // 遮罩层
      loading: true,
            // 选中数组
      ids: [],
      // 折叠面板激活角色
      activeRoles: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 角色+用户数据（后端已分组）
      rolesWithUsers: [],
      // 日历对话框
      calendarOpen: false,
      // 详情对话框
      detailOpen: false,
      // 选中的日期
      selectedDate: new Date(),
      // 传递给详情页的日期
      selectedDateForDetail: '',
      // 选中的用户ID
      selectedUserId: null,
      // 查询参数
      queryParams: {
        userName: null
      },
      // 月度分数数据
      monthlyScores: {},
      // 选中的用户信息
      selectedUserInfo: {}
    }
  },
  created() {
      this.getList()
  },
  mounted() {
      // 确保页面完全加载后也请求数据
      this.getList()
  },
  activated() {
      // 如果使用了 keep-alive，在组件激活时也请求数据
      this.getList()
  },
  watch: {
      // 监听路由变化，确保每次进入页面都请求数据
      '$route'(to, from) {
          if (to.path === '/system/assessManagerAudit') {
              this.getList()
          }
      }
  },
  methods: {
    /** 查询可管理的角色及其员工 */
    getList() {
      this.loading = true
      // 添加时间戳参数防止缓存
      const params = {
        ...this.queryParams,
        _t: Date.now() // 添加时间戳防止缓存
      }
      getAssessRolesWithUsers(params).then(response => {
        // response.data: [{ roleId, roleName, roleKey, users: SysUser[] }]
        const allData = response.data || []
        
        // 过滤数据：只显示主管已审核但经理未审核的用户
        this.rolesWithUsers = allData.map(roleGroup => {
          const filteredUsers = roleGroup.users.filter(user => {
            // 主管已审核 && 经理未审核
            const isSupervisorAudited = user.supervisorAudited === true || user.supervisorAudited === 1
            const isManagerNotAudited = user.managerAudited === false || user.managerAudited === 0 || user.managerAudited === null
            return isSupervisorAudited && isManagerNotAudited
          })
          
          return {
            ...roleGroup,
            users: filteredUsers
          }
        }).filter(roleGroup => roleGroup.users.length > 0) // 只保留有用户的角色组
        
        this.loading = false
      }).catch(error => {
        this.loading = false
        console.error('获取用户列表失败:', error)
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 查看考核日历 */
    handleViewCalendar(row) {
      this.selectedUserId = row.userId
      this.selectedUserInfo = row // 存储用户信息
      this.calendarOpen = true
      // 获取当前月份的分数数据
      this.getMonthlyScores(row.userId)
    },
    /** 获取月度分数数据 */
    getMonthlyScores(userId) {
      const yearMonth = this.formatDate(this.selectedDate, 'yyyy-MM')
      // 这里需要调用获取月度分数的API
      // getMonthDailyScores(yearMonth, userId).then(response => {
      //   this.monthlyScores = response.data || {}
      // })
    },
    /** 日期选择处理 */
    handleDateSelect(date) {
      this.selectedDateForDetail = this.formatDate(date, 'yyyy-MM-dd')
      this.calendarOpen = false
      this.detailOpen = true
    },
    /** 格式化日期 */
    formatDate(date, format) {
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      
      return format
        .replace('yyyy', year)
        .replace('MM', month)
        .replace('dd', day)
    },
    /** 获取日期样式类 */
    getDayClass(data) {
      const today = new Date()
      const date = new Date(data.day)
      
      if (date.toDateString() === today.toDateString()) {
        return 'today'
      }
      return ''
    },
    /** 获取日期分数 */
    getDayScore(day) {
      return this.monthlyScores[day] || null
    },
    /** 获取分数样式类 */
    getScoreClass(score) {
      if (score >= 90) return 'score-high'
      if (score >= 60) return 'score-medium'
      return 'score-low'
    },
    /** 处理日历日期点击 */
    handleDayClick(data) {
      this.selectedDate = new Date(data.day)
      this.handleDateSelect(this.selectedDate)
    },
    /** 处理查看今日考核 */
    handleTodayClick() {
      this.selectedDate = new Date()
      this.handleDateSelect(this.selectedDate)
    },
    /** 判断是否有考核数据 */
    hasAssessData(day) {
      // 这里需要调用判断是否有考核数据的API
      // 例如：getAssessDataByDay(day, this.selectedUserId).then(response => {
      //   return response.data || false
      // })
      return false // 暂时返回false，实际需要调用API
    },
    /** 详情对话框关闭前的处理 */
    handleDetailClose(done) {
      if (done) {
        this.$confirm('确认关闭？')
          .then(_ => {
            done()
          })
          .catch(_ => {})
      } else {
        this.detailOpen = false
      }
    },
    /** 处理提交成功事件 */
    handleSubmitSuccess() {
      this.$message.success('审核提交成功')
      this.detailOpen = false
      // 刷新数据
      this.getList()
    }
  }
}
</script>

<style scoped>
.page-header {
  margin-bottom: 20px;
  padding: 15px 20px;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  border-radius: 8px;
  border-left: 4px solid #409EFF;
}

.page-header h3 {
  margin: 0 0 8px 0;
  color: #333;
  font-size: 18px;
  font-weight: bold;
}

.page-desc {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.calendar-dialog .el-dialog__body {
  padding: 20px;
}

.calendar-dialog .el-dialog__footer {
  padding: 10px 20px;
  border-top: 1px solid #ebeef5;
}

.calendar-container {
  max-height: 500px;
  overflow-y: auto;
}

.calendar-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding: 10px 0;
  border-bottom: 2px solid #409EFF;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  border-radius: 8px;
  padding: 15px;
}

.calendar-title {
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.user-info {
  font-size: 14px;
  color: #666;
  background: rgba(64, 158, 255, 0.1);
  padding: 5px 10px;
  border-radius: 15px;
  border: 1px solid #409EFF;
}

.calendar-day {
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  position: relative;
  min-height: 50px;
  cursor: pointer;
  border-radius: 8px;
  transition: all 0.3s ease;
  border: 1px solid transparent;
}

.calendar-day:hover {
  background-color: #f0f9ff;
  border-color: #409EFF;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.2);
}

.day-number {
  font-size: 14px;
  font-weight: 500;
  color: #333;
}

.day-score {
  font-size: 10px;
  font-weight: bold;
  margin-top: 2px;
  padding: 2px 6px;
  border-radius: 10px;
  min-width: 24px;
  text-align: center;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.score-high {
  background: linear-gradient(135deg, #67C23A, #85ce61);
  color: white;
}

.score-medium {
  background: linear-gradient(135deg, #E6A23C, #ebb563);
  color: white;
}

.score-low {
  background: linear-gradient(135deg, #F56C6C, #f78989);
  color: white;
}

.today {
  background: linear-gradient(135deg, #409EFF, #66b1ff);
  color: white;
  border: 2px solid #409EFF;
}

.today .day-number {
  color: white;
  font-weight: bold;
}

.today .day-score {
  background: rgba(255, 255, 255, 0.2);
  color: white;
  border: 1px solid rgba(255, 255, 255, 0.3);
}

.assess-indicator {
  position: absolute;
  top: 2px;
  right: 2px;
  background: linear-gradient(135deg, #409EFF, #66b1ff);
  color: white;
  border-radius: 50%;
  width: 18px;
  height: 18px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 10px;
  border: 2px solid white;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.4);
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0% {
    transform: scale(1);
    box-shadow: 0 2px 8px rgba(64, 158, 255, 0.4);
  }
  50% {
    transform: scale(1.1);
    box-shadow: 0 4px 16px rgba(64, 158, 255, 0.6);
  }
  100% {
    transform: scale(1);
    box-shadow: 0 2px 8px rgba(64, 158, 255, 0.4);
  }
}

.detail-dialog .el-dialog__header {
  padding: 15px 20px;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  border-bottom: 2px solid #409EFF;
  border-radius: 8px 8px 0 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.detail-dialog .el-dialog__header .el-dialog__title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}

.detail-dialog .el-dialog__header .el-dialog__headerbtn {
  top: 15px;
  right: 15px;
}

.detail-dialog .el-dialog__header .el-dialog__headerbtn .el-icon-close {
  font-size: 22px;
  color: #909399;
  transition: all 0.3s ease;
}

.detail-dialog .el-dialog__header .el-dialog__headerbtn:hover .el-icon-close {
  color: #F56C6C;
  transform: scale(1.1);
}

.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding: 15px;
  border-bottom: 2px solid #ebeef5;
  background: #fafafa;
  border-radius: 8px;
}

.detail-info {
  display: flex;
  align-items: center;
  gap: 15px;
}

.detail-title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

.detail-date {
  font-size: 14px;
  color: #666;
  background: rgba(64, 158, 255, 0.1);
  padding: 5px 12px;
  border-radius: 15px;
  border: 1px solid #409EFF;
}

.detail-user {
  font-size: 14px;
  color: #666;
  background: rgba(103, 194, 58, 0.1);
  padding: 5px 12px;
  border-radius: 15px;
  border: 1px solid #67C23A;
}

.close-btn {
  padding: 8px 12px;
  margin-left: 10px;
  border-radius: 6px;
  transition: all 0.3s ease;
}

.close-btn:hover {
  background-color: #f56c6c;
  color: white;
  transform: scale(1.05);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .calendar-dialog {
    width: 95% !important;
  }
  
  .detail-dialog {
    width: 98% !important;
  }
  
  .calendar-header {
    flex-direction: column;
    gap: 10px;
    text-align: center;
  }
  
  .detail-info {
    flex-direction: column;
    gap: 8px;
    align-items: flex-start;
  }
}

/* 审核状态显示样式 */
.audit-status-display {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.audit-role-row {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 12px;
}

.role-label {
  font-weight: bold;
  color: #606266;
  min-width: 30px;
}

</style>
